package com.yearner.reviewplan.plan;

import com.google.gson.Gson;
import com.yearner.reviewplan.common.exception.NormalException;
import com.yearner.reviewplan.common.model.BaseRepository;
import com.yearner.reviewplan.common.util.MyJdbcUtil;
import com.yearner.reviewplan.plan.model.Plan;
import com.yearner.reviewplan.plan.model.PlanId;
import com.yearner.reviewplan.plan.model.PlanVo;
import com.yearner.reviewplan.plan.model.ReviewDto;
import com.yearner.reviewplan.user.model.Cycle;
import com.yearner.reviewplan.user.model.UserId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.yearner.reviewplan.plan.model.PlanTableEnum.*;

/**
 * @author pengyg
 * @since 2019/10/18
 */
@Component
public class PlanRepresentation extends BaseRepository {
    private final Gson gson;
    private static final Logger log = LoggerFactory.getLogger(PlanRepresentation.class);
    //    private final PlanRepository repository;

    public PlanRepresentation(MyJdbcUtil myJdbcUtil, Gson gson) {
        super(myJdbcUtil);
        this.gson = gson;
//        this.repository = repository;
    }


    public List<Plan> getByPlanId(UserId userId, PlanId planId) {
        String getSqlBefore = String.format("select * from %s where %s in ", TABLE.getColumn(), ID.getColumn());
        String getSqlAfter = String.format("(select %s from %s where %s.%s=? and %s.%s=?)", U2P_PID.getColumn()
                , TABLE_U2P.getColumn(), TABLE_U2P.getColumn(), U2P_USER_ID.getColumn()
                , TABLE_U2P.getColumn(), U2P_PID.getColumn());

        String sql = getSqlBefore + getSqlAfter;
        return new ArrayList<>(jdbcTemplate.query(sql, mapper(), userId.toString(),planId.toString()));
    }

    @Override
    protected RowMapper<Plan> mapper() {
        return (rs, rowNum) -> gson.fromJson(rs.getString(JSON_CONTAIN.getColumn()), Plan.class);
    }

    /**
     * 查询用户所有的plan
     * @param userId 用户id
     * @return List<Plan>
     */
    public List<Plan> getByUserId(String userId) {
        String getSqlBefore = String.format("select * from %s where %s in ", TABLE.getColumn(), ID.getColumn());
        String getSqlAfter = String.format("(select %s from %s where %s.%s=?) ", U2P_PID.getColumn()
                , TABLE_U2P.getColumn(), TABLE_U2P.getColumn(), U2P_USER_ID.getColumn());

        String sql = getSqlBefore + getSqlAfter + " order by updatetime desc ";
        return new ArrayList<>(jdbcTemplate.query(sql, mapper(), userId));
    }

    List<ReviewDto> getReviewDtoByUserId(String userId) {
        String getSqlBefore = String.format("select pid,stageIndex,last_time as lastTime from %s where %s in ", TABLE.getColumn(), ID.getColumn());
        String getSqlAfter = String.format("(select %s from %s where %s.%s=?) ", U2P_PID.getColumn()
                , TABLE_U2P.getColumn(), TABLE_U2P.getColumn(), U2P_USER_ID.getColumn());

        String sql = getSqlBefore + getSqlAfter;
        return new ArrayList<>(jdbcTemplate.query(sql, (rs, rowNum)->{
            ReviewDto reviewDto = new ReviewDto();
            reviewDto.setPid(rs.getString(1));
            reviewDto.setStageIndex(rs.getInt(2));
            reviewDto.setLastTime(new Date(rs.getLong(3)));
            return reviewDto;
        }, userId));
    }

    /**
     * 根据相关信息，筛选需要复习的plan
     * @param reviewDtoList 剔除具体内容的plan信息列表
     * @param cycle 用户设置的阶段与间隔
     * @return List<PlanVo>
     */
    public List<PlanVo> getNeedReview(List<ReviewDto> reviewDtoList, Cycle cycle) {
        if (reviewDtoList == null ) {
            return new ArrayList<>();
        }
        List<String> needIdList = new ArrayList<>();
        // 遍历检查复习阶段，以及间隔时间是否达到要求
        for (ReviewDto dto:reviewDtoList) {
            if (cycle.calculate(dto.getStageIndex(), dto.getLastTime().getTime())) {
                needIdList.add(dto.getPid());
            }
        }
        if (needIdList.isEmpty()) {
            return new ArrayList<>();
        }
        //查询相关语句
        String sql = String.format("select * from %s where %s in (:pidList)", TABLE.getColumn(), ID.getColumn());
        NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(super.myJdbcUtil.getDataSource());
        HashMap<String, Object> pidMap = new HashMap<>();
        pidMap.put("pidList", needIdList);
        List<Plan> plans = npjt.query(sql, pidMap, mapper());
        //构建PlanVo
        List<PlanVo> need = new ArrayList<>();
        for (Plan plan : plans) {
            need.add(new PlanVo(plan));
        }
        return need;
    }

//    private List<String> getUserPlans(String userId) {
//        String sqlUserToPlan = String.format("select * from %s where %s = ?",
//                TABLE_U2P.getColumn(), U2P_USER_ID.getColumn());
//
//        List<String> query = jdbcTemplate.query(sqlUserToPlan, (rs, rowNum) ->{
//            String pid = rs.getString(U2P_PID.getColumn());
//            return (pid == null || pid.isEmpty()) ? null : pid;
//        }, userId);
//
//        //如果为空则返回，如果不为空，就消除null
//        if (query.isEmpty()) {
//            return query;
//        }
//        //遍历，消除null
//        List<String> planList = new ArrayList<>();
//        for (int i = 0, length = query.size(); i < length; i++) {
//            if (query.get(i) == null) {
//                continue;
//            }
//            planList.add(query.get(i));
//        }
//        return planList;
//    }
}
